<style scoped>
  .weui-form-preview__hd label, .weui-form-preview__hd em {
    font-size: .9em !important;
  }
  .rj-cell.max span{
    font-size: 16px;
    padding-right: 20px;
  }
  .rj-cell label {
    color: #333;
    font-size: 14px;
    width: 44%;
    display: inline-block;
    padding: 5px 3%;
    text-align: right;
  }
  .rj-cell span {
    font-size: 14px;
    color: #333;
    display: inline-block;
    width: 50%;
  }
  .rj-cell.note label{
    float: left;
  }
  .rj-cell.note span{
    width: 80%;
    display: inline-block;
  }
  .weui-cells {
    margin-top: 0;
  }
  .weui-cells_form {
    background: #fbfbfb;
  }
  .weui-cell {
    background: #fff;
  }
  #acts span {
    font-size: 14px;
  }
  .halfbtn {
    display: inline-block;
    width: 49%;
  }
  .weui-label{
    /*width: 130px;*/
    text-align: left;
  }
  *{
    list-style:none;
  }
  #acts {
    font-size: 0;
  }
  #acts span {
    font-size: 14px;
  }
</style>
<template>
  <div class="comon">
    <div class="rj-wrap">
     {{title}}
      <a href="javascript:;" @click="$router.back(-1)" style="position: absolute; left: 10px; top: 8px">
        <img src="@/assets/back.png" style="width: 20px" />
      </a>
    </div>
    <div class="weui-cells weui-cells_form">
        <form method="post" id="formid">
          <input type="hidden" name="type" :value="pickinglist.picktype" />
          <input type="hidden" name="produceplanid" :value="pickinglist.produceplanid" />
          <input type="hidden" name="linkedid" :value="pickinglist.guid" />
          <input type="hidden" name="srguid" :value="pickinglist.strmid" />
          <input type="hidden" name="departid" :value="pickinglist.departmentid" />
          <input type="hidden" name="orgguid" :value="pickinglist.orgid" />
          <input type="hidden" name="status" value="1" />
          <div class="cellgroup">
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">领料单编号</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" readonly :value="pickinglist.code" name="">
            </div>
          </div>
            <div class="weui-cell">
              <div class="weui-cell__hd"><label class="weui-label">入库库房</label></div>
              <div class="weui-cell__bd">
                <input class="weui-input" readonly name="" :value="pickinglist.strname">
              </div>
            </div>
            <div class="weui-cell">
              <div class="weui-cell__hd"><label class="weui-label">库存组织</label></div>
              <div class="weui-cell__bd">
                <input class="weui-input" readonly  type="text"  name="orgname" :value="pickinglist.orgname">
              </div>
            </div>
            <div class="weui-cell">
              <div class="weui-cell__hd"><label class="weui-label">入库类型</label></div>
              <div class="weui-cell__bd">
                <input class="weui-input" readonly name="typeName" value="生产退料">
              </div>
            </div>
            <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">所在班组</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" readonly  type="text"  name="" :value="pickinglist.departmentname">
            </div>
          </div>

          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">创建时间</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" readonly type="text" name="" :value="pickinglist.createtime">
            </div>
          </div>
        </div>
          <MaterRetApplyItem v-for="(item, index) in oitems" :key="index" :itemNo="item" :isLast="index+1 == oitems.length" :pickid="guid" :picktype="pickinglist.picktype" :products="products" @doAddItem="addItem(index + 1)" @doDelItem="delItem"></MaterRetApplyItem>
          <div ref="actHtml" class="fixcont">
            <div class="weui-btn-area">
              <a class="weui-btn weui-btn_primary halfbtn subbtn"  href="javascript:" @click="send">提交</a>
              <a class="weui-btn weui-btn_primary halfbtn subbtn" v-if="refuseflag == 1" href="javascript:" @click="rejectIt">拒绝</a>
              <a class="weui-btn weui-btn_primary halfbtn" v-else href="javascript:" @click="$router.back(-1)" id="sub">返回</a>
            </div>
          </div>
      </form>
    </div>
    <div id="bmlogs">
      <OperationLogs2 :nodeid="nodeid" :orderid="guid" :srguid="pickinglist.strmid" :departid="pickinglist.departmentid"></OperationLogs2>
    </div>
  </div>
</template>

<script>
  import MaterRetApplyItem from "./MaterRetApplyItem";
  import OperationLogs2 from '../../common/OperationLogs2'

  export default {
    name: 'AddMaterialRetApply',
    data () {
      return {
        openid: localStorage.openid,
        guid: '',
        type: 1,
        pickinglist: {},
        items: [],
        products: [],
        specifications: [],
        nodeid: '',
        title: '',
        oitems: [0],
        refuseflag: '',
        refuseNodes: []
      }
    },
    components: {MaterRetApplyItem, OperationLogs2},
    created() {
      window.addEventListener('setItem', ()=> {
        this.openid = localStorage.getItem('openid');
      })
    },
    mounted () {
      //提交操作定位到页面底部
      //$('#bmlogs').css('margin-bottom', this.$refs.actHtml.offsetHeight);

      let that = this;
      this.guid = this.$route.query.guid;
      this.type = this.$route.query.type;
      this.nodeid = this.$route.query.nodeid;
      this.title = this.$route.query.title;

      this.refuseflag = this.$route.query.refuseflag;
      if (this.refuseflag == 1) {
        this.getRefuseNodes();
      }

      //获取回显数据
      this.getApplyInfo(this.$route.query.guid);

      //添加明细item
      // $('form').on('click', '#addItem', function () {
      //   $('.oitem:hidden').eq(0).find('input').attr("disabled",false);
      //   $('.oitem:hidden').eq(0).find('textarea').attr("disabled",false);
      //   $('.oitem:hidden').eq(0).find('select').attr("disabled",false);
      //   $('.oitem:hidden').eq(0).show();
      //   updateActBtns();
      // })
      // //删除明细
      // $('form').on('click', '#delItem', function () {
      //   var elm = $(this).parents('.oitem');
      //   $.confirm("确定要删除该货品明细吗？", function () {
      //     elm.find('input').val('');
      //     elm.find('textarea').val('');
      //     elm.hide();
      //     $('.oitem:hidden').eq(0).find('input').attr("disabled",true);
      //     $('.oitem:hidden').eq(0).find('textarea').attr("disabled",true);
      //     $('.oitem:hidden').eq(0).find('select').attr("disabled",true);
      //     updateActBtns();
      //   })
      // })
      //调整添加、删除按钮位置
      function updateActBtns() {
        $('#acts').remove();
        var actHtml = '<p id="acts" style="float: right;color: #1aad19;"><span id="addItem" style="padding-right: 5px;">添加</span><span>|</span><span id="delItem" style="padding-left: 5px;">删除</span></p>';

        if ($('.oitem:visible').length == 5) {
          actHtml = '<p id="acts" style="float: right;color: #1aad19;"><span id="delItem" style="padding-left: 5px;">删除</span></p>';
        } else if ($('.oitem:visible').length == 1) {
          var actHtml = '<p id="acts" style="float: right;color: #1aad19;"><span id="addItem" style="padding-right: 5px;">添加</span></p>';
        }
        $('.oitem:visible:last').find('.weui-cells__title').append(actHtml);
      }
    },
    computed: {

    },
    methods: {
      addItem: function(index) {
        this.oitems.push(index);
      },
      delItem: function() {
        this.oitems.pop();
      },
      getApplyInfo: function(guid) {
        this.axios({
          method: 'get',
          url: '/produce/Whinapply!getProducts.action',
          params: {pickinglistid: guid}
        }).then((response) => {
          if (response.data.msg == 'success') {
            let data = response.data;
            this.pickinglist = data.pickinglist;
            this.items = data.items;
            this.products = data.products;
            this.specifications = data.specifications;
          }  else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
          //不不设置提示
        } else {
            this.toastError("系统错误");
          }

        })
      },
      send: function() {
        if (!this.checkNull(this.pickinglist.orgname)) {
          this.toastText('库存组织为空，不能退料！');
          return false;
        } else if (!this.checkEmy('product')) {
          this.toastText('产品有误！')
          return false;
        }
        if(!this.checkEmy('specif')) {
          this.toastText('规格有误！')
          return false;
        }
        if(this.picktype != 1 && !this.checkProduct()) {
            this.toastText('货品明细产品重复！')
            return false;
        }

        //防止重复提交
        $('.subbtn').attr("disabled",true).css("pointer-events","none");
        //显示提交状态
        $.showLoading("正在提交");

        let that  = this;
        let postData = this.serialize2Obj($("#formid").serializeArray());
        postData.nodeid = this.nodeid;

        this.axios({
          method: 'post',
          url: '/produce/Materialretapply!OutDate.action?pickinglistid=' + this.guid,
          params: postData
        }).then(response => {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();

            console.log(response);
          if(response.data.info == "success"){
            this.toastText('操作成功!');
            this.$router.push({name: 'PickingList', query: {guid:that.pickinglist.guid}});

          }else if (response.data.info == 'outlogin'){
            this.toastText('请重新登录!');
          } else if (response.data.info == 'canotopt') {
            this.toastText('不允许的操作！');
          } else if (response.data.info == 'error'){
            this.toastError('系统错误!');
          }
        }).catch(function (error) {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();
          that.toastError('系统错误');
        });

      },
      //判断明细产品是否重复
      checkProduct: function () {
        let parr1 = [];
        let parr2 = [];
        for (let i=0; i<$('.oitem').length; i++) {
          parr1.push({[$('.product').eq(i).val()]: $('.specif').eq(i).val()});
          parr2.push({[$('.product').eq(i).val()]: $('.specif').eq(i).val()});
        }
        //json数组去重
        for (var i = 0; i < parr2.length; i++) {
          for (var j =i+1; j <parr2.length; ) {
            if (Object.keys(parr2[i])[0] == Object.keys(parr2[j])[0] && Object.values(parr2[i])[0] == Object.values(parr2[j])[0] ) {
              parr2.splice(j, 1);//去除重复的对象；
            }else {
              j++;
            }
          }
        }
        return parr1.length == parr2.length ? true : false;
      },
      getRefuseNodes: async function() {
        let that = this;
        await this.axios({
          method: 'get',
          url: '/sales/Flowtempnode!getFoRefuseNodes.action',
          params: {orderid: this.guid, nodeid: this.nodeid}
        }).then(response => {

          if (response.data.msg == 'success') {
            this.refuseNodes = response.data.optNodes.map(function (item) {
              return {text: item.name,
                onClick: function() {
                  $.confirm("确定要将订单回退到 " + item.name + " 节点？", function() {
                    that.doReject(item.guid, item.name, item.operatorid);
                  })
                }};
            });
          } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
            //不不设置提示
          } else {
            this.toastText('获取可回退节点数据失败!');
          }
        });
      },
      rejectIt: function () {
        if (!this.checkEmy('opinion')) {
          this.toastText('意见不能为空！');
          return false;
        }
        console.log('this.refuseNodes:', this.refuseNodes)
        if (this.refuseNodes.length > 0) {
          $.actions({
            title: '选择回退节点',
            actions: this.refuseNodes
          });
        } else {
          this.toastText('无可回退节点！');
          return false;
        }
      },
      doReject: function (refuseNodeid, refuseNodename, refuseOperatorid) {
        let that = this;

        //防止重复提交
        $('.subbtn').attr("disabled",true).css("pointer-events","none");
        //显示提交状态
        $.showLoading("正在提交");

        let postData = {};
        postData.imgids = this.images.serverId.join(',');
        // postData.imgids = '';
        postData.transferid = this.guid;
        postData.opinion = ($('#opinion').val() || '') + ' 退回到' + refuseNodename;
        postData.nodeid = this.nodeid;
        postData.refuseNodeid = refuseNodeid;
        postData.backUserid = refuseOperatorid;
        this.axios({
          method: 'post',
          url: '/produce/Pickinglist!refuse.action',
          params: postData
        }).then((response) => {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();

          if (response.data.msg == 'success') {
            this.toastSuccess('提交成功!');
            this.$router.push({name: 'PickingList'});
          } else if (response.data.msg == 'canotopt') {
            this.toastText('不允许的操作！');
          } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
            //不不设置提示
          } else {
            this.toastError('系统错误');
          }
        }).catch(function (error) {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();
          that.toastError('系统错误');
        });
      },
      openLogs: function() {
        this.$router.push({name: 'OperationLogs2', query: {orderid: this.guid, srguid: this.pickinglist.strmid, departid: this.pickinglist.departmentid}});
      }

    }
  }


</script>
